package com.medvalley.tcm.controller;

import com.alibaba.fastjson.JSON;
import com.medvalley.tcm.weixin.JSApiTicket;
import com.medvalley.tcm.weixin.WXConfig;
import com.medvalley.tcm.weixin.WXException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by linsong on 2018/3/18.
 */
@RestController
public class WXJSApiController extends BaseController {

    @Autowired
    private JSApiTicket jsApiTicket;

    @RequestMapping("/wx/jsapi")
    public String getAPIConfig(String org, String url) throws NoSuchAlgorithmException, WXException {

        Map<String, String> resultMap = new HashMap<>();
        Map<String, String> paraMap = new TreeMap<>();
        String nonceStr = getNonceStr();
        String jsapiTicket = jsApiTicket.getTicket();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        paraMap.put("noncestr", nonceStr);
        paraMap.put("jsapi_ticket", jsapiTicket);
        paraMap.put("timestamp", timeStamp);
        paraMap.put("url", url);
        String sign = this.createSign(paraMap);
        resultMap.put("appId", WXConfig.APP_ID);
        resultMap.put("timestamp", timeStamp);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("signature", sign);
        resultMap.put("org", org);
        return JSON.toJSONString(resultMap);

    }

    private String getNonceStr() {
        return UUID.randomUUID().toString();

    }

    private String createSign(Map<String, String> para) throws NoSuchAlgorithmException {
        String str = this.generateLinkString(para);
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }

    private String generateLinkString(Map<String, String> para) {
        Set<Map.Entry<String, String>> entrySet = para.entrySet();
        String linkStr = "";
        for (Map.Entry<String, String> keyValue : entrySet) {
            String key = keyValue.getKey();
            String value = keyValue.getValue();
            linkStr = linkStr + key + "=" + value + "&";
        }
        linkStr = linkStr.substring(0, linkStr.length() - 1);

        return linkStr;
    }

}
